module scene {

    import RankPage = page.RankPage;

    export class NormalGameScene extends eui.Component {

        public gamgPageBg: eui.Image;

        public rootGroup: eui.Group;

        public backBtn: eui.Image;

        public btnFriendHelp: eui.Image;

        public btnCoinTip: eui.Image;

        public btnFreeTip: eui.Image;

        public gameSkillCon: eui.Group;

        public txtCoin: egret.TextField;

        public gameGroup: eui.Group;

        private txtLevel: egret.TextField;

        private pkPage: page.PkFriendPage;

        public pkFriendGroup: eui.Group;

        private startAt: number;

        private endAt: number;

        private costSeconds: number;

        private skill1: eui.Image;

        private skill2: eui.Image;

        private skill3: eui.Image;

        private score: number = 0;

        private level: number = 1;

        private skillArr = [0, 0, 0];

        private gameStoneText: eui.Label;

        private Stone: number

        private skill1Con: eui.Group;

        private treasureBox: eui.Image

        private TreasureBoxScene: scene.TreasureBoxScene

        private AddStoneCon: eui.Group
        private isBeginAdd: boolean = false;
        private skill1Add: boolean;
        private skill2Add: boolean;
        private skill3Add: boolean;
        private running: boolean = true;
        private destoryOne: boolean;
        private destoryAll: boolean;
        private stoneScene: scene.AddStoneScene;
        //创建Block仓库
        private blockCon: eui.Group;
        private NowLevelText: eui.Label;
        private targetText: eui.Label;
        private gameScore: eui.Label;
        private levelScoreArr = [500, 1200, 2000, 3000, 4200, 5500, 6800, 8000, 9000,10500, 12400, 14000, 15500, 17000, 19000, 21000, 23000, 25000, 27000, 285000, 30000, 31500, 335000, 35000, 36500, 38000, 40000, 42000, 45000, 47000, 50000, 53000, 56000, 59000, 62000, 65000, 70000, 80000, 90000, 100000]
        private targetScore: number;
        private gameCon: eui.Group
        private animTime = 200;
        private diff: number;
        private minGroupSize = 2;
        private selectBlock = [];
        private maxCB: number;
        private status: string;
        private ele: egret.Bitmap;
        private picArr = ['block1_png', 'block2_png', 'block3_png', 'block4_png', 'block5_png']
        private randomX: number
        private randomY: number
        private data = [];
        private touchAble: boolean = true;     
        private gameFinishSkill1: eui.Image;   
        private gameFinishSkill2: eui.Image;   
        private gameFinishSkill3: eui.Image;   
        private gameProgress2: eui.Image;
        private gameProgress1: eui.Image;
        private begainAddPage: scene.BeginAddPage;
        private goodBox: egret.Bitmap;
        private coolMovie: egret.tween.TweenGroup;
        private boomMovie: egret.tween.TweenGroup;
        private verygoodMovie: egret.tween.TweenGroup;
        private smartMovie: egret.tween.TweenGroup;
        private addStoneMovie: egret.tween.TweenGroup;
        private starScoreAdd = false
        private __timeobjArrange;
        private canPlaySound: boolean = true;
        private canAddSkill: boolean = true;
        private randomAdd: number;
        private star;
        private isGameOver: boolean = false;
        private scorePercenage: number;
        private gameProgress3: eui.Image
        private addSkill1: egret.tween.TweenGroup
        private addSkill2: egret.tween.TweenGroup
        private addSkill3: egret.tween.TweenGroup
        private useSkill1Movie: egret.tween.TweenGroup
        private useSkill2Movie: egret.tween.TweenGroup
        private useSkill3Movie: egret.tween.TweenGroup
        private boxAddSkill1Movie: egret.tween.TweenGroup
        private boxAddSkill2Movie: egret.tween.TweenGroup
        private boxAddSkill3Movie: egret.tween.TweenGroup
        private reliveScene: scene.ReliveScene
        private successScene: scene.SuccessScene
        private skill1Text: eui.Label;
        private skill2Text: eui.Label;
        private skill3Text: eui.Label;
        private timer;
        private guangboMovie: egret.tween.TweenGroup
        private rliveNum: number = 3;
        private hasTreasureScene: boolean = false;


        public constructor() {
            super();
            this.addEventListener(eui.UIEvent.COMPLETE, this.onComplete, this);
            this.skinName = "gamePageSkin";
        }

        public onComplete(eve: eui.UIEvent): void {

            this.gamgPageBg.width = manager.DisplayManager.STAGE_WIDTH;
            this.gamgPageBg.height = manager.DisplayManager.STAGE_HEIGHT;

            this.skill1Con.addEventListener(egret.TouchEvent.TOUCH_TAP, this.DestroyOneHandler, this);

            this.skill2.addEventListener(egret.TouchEvent.TOUCH_TAP, this.ExchangeLocationHandler, this);

            this.skill3.addEventListener(egret.TouchEvent.TOUCH_TAP, this.DestroyAllHandler, this);

            this.backBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onBacked, this);

            this.Stone = wx.getStorageSync('stone').stone || 0

            this.gameStoneText.text = `${this.Stone}`

            this.AddStoneCon.addEventListener(egret.TouchEvent.TOUCH_TAP, this.showStoneScene, this)

            this.createGameView()
            
            this.begainAddPage = new scene.BeginAddPage()
            this.addChild(this.begainAddPage)
            this.begainAddPage.addEventListener(events.BeginAddEvent.BEGIN_ADD, this.beginAdd, this)
            this.begainAddPage.addEventListener(events.BeginAddRejectEvent.BEGIN_ADD_REJECT, this.BeginAddClose, this)
        }
 
        private createGameView(): void {
            console.log('createGameView')     

            this.gameProgress2.width = 0
            this.gameProgress2.mask = this.gameProgress3            
            this.randomAdd = Math.floor(Math.random() * 3)
            if(this.randomAdd <= 1){
                this.gameFinishSkill1.scaleX = this.gameFinishSkill1.scaleY = 1

                this.gameFinishSkill1.visible = true
                this.gameFinishSkill2.visible = false
                this.gameFinishSkill3.visible = false
            }else if(this.randomAdd <= 2){
                this.gameFinishSkill2.scaleX = this.gameFinishSkill2.scaleY = 1
                
                this.gameFinishSkill1.visible = false
                this.gameFinishSkill2.visible = true
                this.gameFinishSkill3.visible = false
            }else if(this.randomAdd <= 3){
                this.gameFinishSkill3.scaleX = this.gameFinishSkill3.scaleY = 1
                
                this.gameFinishSkill1.visible = false
                this.gameFinishSkill2.visible = false
                this.gameFinishSkill3.visible = true
            }

            this.randomX = Math.floor(Math.random() * 10 )
            this.randomY = Math.floor(Math.random() * 10 )
            this.blockCon.removeChildren()
            this.NowLevelText.text = `关卡: ${this.level || 1}`
            this.targetScore = this.levelScoreArr[(this.level || 1) - 1]
            this.targetText.text = `目标: ${this.levelScoreArr[(this.level || 1) - 1]}`
            this.gameScore.text = `${this.score || 0}`
            this.maxCB = 1000 >= this.targetScore ? 7 : 5;
            var a = 5000 >= this.targetScore ? 23 : 30;
            this.diff = 4
            do this.randBlocks();
            while (!this._checkEnd(a));
            this.status = "play";
        }

        private createBlock(a, b, c, d, nnn) {
            console.log('生成方块')
            this.ele = null
            this.ele = manager.ResManager.getBitmap(this.picArr[b - 1])
            this.ele.type = b || 0;
            this.ele.width = 69;
            this.ele.height = 69;
            this.ele.x = this.ele.width * c + c;
            this.ele.y = this.ele.height * d + d - 700;
            this.ele.touchEnabled = true;
            this.ele.addEventListener(egret.TouchEvent.TOUCH_TAP, this.click, this)
            this.blockCon.addChild(this.ele);
            this.ele.mark = false
            this.ele.visible = false
            if(this.randomX === c && this.randomY === d){
                console.log('创建宝箱')
                this.ele.mark = true
                this.goodBox = manager.ResManager.getBitmap("functonPage_json.treasureBox");
                this.goodBox.width = this.ele.width - 20
                this.goodBox.height = this.ele.height - 20
                this.goodBox.x = this.ele.x + (this.ele.width - this.goodBox.width) / 2;
                this.goodBox.y = this.ele.y + (this.ele.height - this.goodBox.height) / 2; 
                this.goodBox.visible = false  
                this.blockCon.addChild(this.goodBox)
            }



            return this.ele
        }

        private promptTimer;
        private promptTime = 0;

        private locationY = []

        private blockMovie(){
            this.recentScore()
            this.promptTimer = setInterval(() => {
                this.promptTime ++
                if(this.promptTime == 3){
                    this.onPrompt()
                }
            }, 1000)
            let b = 9
            let c = 9
            let timer = setInterval(() => {
                if(b < 1){
                    clearInterval(timer)
                }
                this.createTimer(b, c)
                b --                
            },40)
        }

        private createTimer(b, c){
            let timer1 = setInterval(() => {
                if(c < 1){
                    clearInterval(timer1)
                    if(b == 0){
                        this.touchAble = true
                    }
                }
                this.data[b][c].visible = true

                egret.Tween.get(this.data[b][c])
                    .to({y: this.data[b][c].y + 700}, 200)
                if(this.data[b][c] !== null && this.data[b][c].mark === true){
                    this.goodBox.visible = true
                    
                    egret.Tween.get(this.goodBox).to({
                        y: this.data[b][c].y + (this.data[b][c].height - this.goodBox.height) / 2 + 700
                    }, 200)               
                }
                c --                
            }, 60)
        }

        //使用道具相关函数
        private DestroyOneHandler(): void {
            manager.StatisticsManager.click(162)
            if (!this.running) return
            if (this.skillArr[0] == 0) {

                if(this.Stone >= 15){
                    this.Stone -= 15
                    this.setStone(this.Stone)
                    this.skillArr[0] += 1
                    this.updateSkillImg()     
                    manager.SoundManager.playSound("getSkillMusic_mp3")              
                }else{
                    this.stoneScene = new scene.AddStoneScene()
                    this.addChild(this.stoneScene)
                    this.stoneScene.addEventListener(events.AddStoneEvent.ADD_STONE, this.addStone, this)
                    this.stoneScene.addEventListener(events.AddStoneRejectEvent.ADD_STONE_REJECT, this.addStonePageClose, this)
                    return                    
                }
            }
            manager.SoundManager.playSound("skill1Music_mp3")
            this.useSkill1Movie.play(0)            
            this.timer = setInterval(() => {
                this.useSkill1Movie.play(0)
            }, 1000)
            this.running = false
            this.destoryOne = true
            this.skillArr[0] = this.skillArr[0] - 1
            this.updateSkillImg()
        }
        private ExchangeLocationHandler(): void {
            manager.StatisticsManager.click(163)
            if (this.skillArr[1] == 0) {
                if(this.Stone >= 15){
                    this.Stone -= 15
                    this.setStone(this.Stone)
                    this.skillArr[1] += 1
                    this.updateSkillImg()     
                    manager.SoundManager.playSound("getSkillMusic_mp3")                                   
                }else{
                    this.stoneScene = new scene.AddStoneScene()
                    this.addChild(this.stoneScene)
                    this.stoneScene.addEventListener(events.AddStoneEvent.ADD_STONE, this.addStone, this)
                    this.stoneScene.addEventListener(events.AddStoneRejectEvent.ADD_STONE_REJECT, this.addStonePageClose, this)
                    return                    
                }
            }
            manager.SoundManager.playSound("skill2Music_mp3")
            this.skillArr[1] = this.skillArr[1] - 1
            this.updateSkillImg()
            //技能效果
            let exchangeArr = []
            let array = this.data;
            array.forEach(item => {
                let m = item.length,
                    t, i;
                while (m) {
                    i = Math.floor(Math.random() * m--);
                    t = item[m];
                    item[m] = item[i];
                    item[i] = t;
                }
            })
            let m = array.length,
                t, i;
            while (m) {
                i = Math.floor(Math.random() * m--);
                t = array[m];
                array[m] = array[i];
                array[i] = t;
            }
            this.__timeobjArrange = setTimeout(() => {
                this.arrange()
            }, this.animTime)


        }
        private DestroyAllHandler(): void {
            manager.StatisticsManager.click(164)
            if (!this.running) return
            if (this.skillArr[2] == 0) {
                if(this.Stone >= 15){
                    this.Stone -= 15
                    this.setStone(this.Stone)
                    this.skillArr[2] += 1
                    this.updateSkillImg()  
                    manager.SoundManager.playSound("getSkillMusic_mp3")                                      
                }else {
                    this.stoneScene = new scene.AddStoneScene()
                    this.addChild(this.stoneScene)
                    this.stoneScene.addEventListener(events.AddStoneEvent.ADD_STONE, this.addStone, this)
                    this.stoneScene.addEventListener(events.AddStoneRejectEvent.ADD_STONE_REJECT, this.addStonePageClose, this)
                    return                    
                }         
            }
            this.useSkill3Movie.play(0)            
            this.timer = setInterval(() => {
                this.useSkill3Movie.play(0)
            }, 1000)
            this.running = false
            this.destoryAll = true
            this.skillArr[2] = this.skillArr[2] - 1
            this.updateSkillImg()
        }

        private click(e): void {
            this.promptTime = 0

            this.data.forEach(item => {
                item.forEach(ele => {
                    if(ele && ele.alpha !== 1){
                        ele.alpha = 1
                        egret.Tween.removeTweens(ele)
                    }
                })
            })

            if (this.touchAble == true) {
                let xNum = Math.floor((e.stageX - this.blockCon.x) / 70)
                let yNum = Math.floor((e.stageY - this.blockCon.y) / 70)

                egret.Tween.get(this.data[xNum][yNum])
                    .to({alpha: 0.8}, 200)
                    .to({alpha: 1}, 200)
                

                if (this.running) {
                    let ele = this.data[xNum][yNum]
                    ele.check ? this.ruin(ele) : this.select(ele)
                    this.normalClick(e)
                }else if (this.destoryOne) {
                    clearInterval(this.timer)
                    this.useSkill1(e)
                } else if (this.destoryAll) {
                    clearInterval(this.timer)                    
                    this.useSkill3(e)
                }
            }
        }

        private normalClick(e): void {
            let xNum = Math.floor((e.stageX - this.blockCon.x) / 70)
            let yNum = Math.floor((e.stageY - this.blockCon.y) / 70)
            let ele = this.data[xNum][yNum]
            ele.check ? this.ruin(ele) : this.select(ele)
        }

        private useSkill1(e) {
            manager.SoundManager.playSound("skill1Music_mp3")            
            this.running = true
            this.destoryOne = false
            let xNum = Math.floor((e.stageX - this.blockCon.x) / 70)
            let yNum = Math.floor((e.stageY - this.blockCon.y) / 70)
            this.data[xNum][yNum].parent.removeChild(this.data[xNum][yNum])

            if(this.data[xNum][yNum].mark == true){
                manager.SoundManager.playSound("boxMusic_mp3")
                this.hasTreasureScene = true
                this.TreasureBoxScene = new scene.TreasureBoxScene(this.level)
                this.addChild(this.TreasureBoxScene)
                this.TreasureBoxScene.addEventListener(events.AddTreasureBoxEvent.ADD_TREASURE, this.addTreasure, this)
                this.TreasureBoxScene.addEventListener(events.CloseTreasureBoxPageEvent.CLOSE_TREASURE, this.closeTreasureScene, this)

            }
            this.data[xNum][yNum] = null
            this.setScore(this.score, 10)
            this.__timeobjArrange = setTimeout(() => {
                this.arrange()
            }, this.animTime)
        }
        private useSkill3(e) {
            manager.SoundManager.playSound("skill1Music_mp3")            
            this.running = true
            this.destoryAll = false
            let xNum = Math.floor((e.stageX - this.blockCon.x) / 70)
            let yNum = Math.floor((e.stageY - this.blockCon.y) / 70)
            let nType = this.data[xNum][yNum].type
            let SameNum = 1;
            let SameArr = [];
            this.data.forEach(item => {
                item.forEach(aa => {
                    if (aa != null) {
                        if (aa.type == nType) {
                            SameNum++
                            aa.parent.removeChild(aa)
                            this.data[aa.x / 70][aa.y / 70] = null
                            if(aa.mark == true){
                                manager.SoundManager.playSound("boxMusic_mp3")
                                this.hasTreasureScene = true                                
                                this.TreasureBoxScene = new scene.TreasureBoxScene(this.level)
                                this.addChild(this.TreasureBoxScene)
                                this.TreasureBoxScene.addEventListener(events.AddTreasureBoxEvent.ADD_TREASURE, this.addTreasure, this)
                                this.TreasureBoxScene.addEventListener(events.CloseTreasureBoxPageEvent.CLOSE_TREASURE, this.closeTreasureScene, this)
                            }
                        }
                    }
                })
            })
            let SameX = SameNum * SameNum
            if (SameNum >= 20) {
                SameNum = 20
            }

            this.setScore(this.score, SameNum * SameNum)
            this.onScoreProgress(this.score, this.levelScoreArr[this.level - 1])
            this.__timeobjArrange = setTimeout(() => {
                this.arrange()
            }, this.animTime)
        }



        private playSound(info): void {
            var loader: egret.URLLoader = new egret.URLLoader();
            loader.addEventListener(egret.Event.COMPLETE, function loadOver(event: egret.Event) {
                var sound: egret.Sound = loader.data;
                sound.play(0, 1);
            }, this);
            loader.dataFormat = egret.URLLoaderDataFormat.SOUND;
            loader.load(new egret.URLRequest(info));
        }

        private randBlocks() {
            this.data = [];
            this.blockCon.removeChildren()
            let a = this.k(1, 5);
            let b = this.k(1, 5);
            let c = this.k(1, 5);
            let d = this.k(1, 5);
            let e = this.k(1, 5);
            let nnn = 0
            for (let a = 0; a < 10; a++) {
                c = [];
                for (let b = 0; b < 10; b++) this.k(0, this.maxCB) < this.diff && (e =
                    this.k(1, 5)), d = this.createBlock(this, e, a, b, nnn), c.push(d);
                this.data.push(c)
            }
        }
        private _checkEnd(a ? ) {
            a = a || this.minGroupSize;
            for (var b = 0; b < this.data.length; b++)
                for (var c = 0; c < this.data[b].length; c++)
                    if (this._friends(this.data[b][c]).length >= a) return !1;
            return !0
        }
        private _friends(a) {
            function b(a) {
                var b;
                let xx = a.x / 70;
                let yy = a.y / 70;
                e.data[xx - 1] && (b = e.data[xx - 1][yy]) && b.type == a.type && c(
                    b);
                e.data[xx + 1] && (b = e.data[xx + 1][yy]) && b.type == a.type && c(
                    b);
                (b = e.data[xx][yy - 1]) && b.type == a.type && c(b);
                (b = e.data[xx][yy + 1]) && b.type == a.type && c(b);
            }

            function c(a) {
                var b;
                a: {
                    for (b = 0; b < d.length; b++)
                        if (d[b] == a) break a;
                    b = !1
                }!1 === b && d.push(a)
            }
            if (!a) return [];
            var d = [],
                e = this;
            d.push(a);
            for (a = 0; a < d.length; a++) b(d[a]);
            return d
        }
        private k(a, b) {
            a = Math.round(a);
            b = Math.round(b);
            return Math.round((b - a) * Math.random()) + a
        }

        private ruin(a) {
            let that = this
            this.touchAble = false
            if (this.selectBlock.length >= 8 && this.selectBlock.length < 15) {
                this.coolMovie.play(0)
                manager.SoundManager.playSound("coolMusic_mp3")
            } else if (this.selectBlock.length >= 15 && this.selectBlock.length < 20) {
                this.verygoodMovie.play(0)
                manager.SoundManager.playSound("veryGood_m4a")
            } else if (this.selectBlock.length >= 20 && this.selectBlock.length < 25) {
                this.boomMovie.play(0)
                manager.SoundManager.playSound("boomMusic_mp3")
            } else if (this.selectBlock.length >= 25) {
                this.smartMovie.play(0)
                manager.SoundManager.playSound("smartMusic_mp3")
            }
            if ("play" != this.status) return !1;
            var b = this;
            a = this.selectBlock.length;
            var c
            if(this.starScoreAdd == true){
                c = this.selectBlock.length * this.selectBlock.length + Math.floor(this.selectBlock.length * this.selectBlock.length * 0.2)
            }else{
                c = this.selectBlock.length * this.selectBlock.length
            }
            let d = 0
            let timer = setInterval(() => {
                if(d >= this.selectBlock.length - 1){
                    clearInterval(timer)
                    this.setScore(this.score, c);
                    this.onScoreProgress(this.score, this.levelScoreArr[(this.level || 1) - 1]);
                    clearTimeout(this.__timeobjArrange);
                    this.__timeobjArrange = setTimeout(function () {
                        b.arrange()
                    }, 200)
                }
                this.ruinItem(a, this.selectBlock[d])
                this.data[this.selectBlock[d].x / 70][this.selectBlock[d].y / 70] = null; 
                d ++                                                  
            }, 30)
            let openDataContext = wx.getOpenDataContext();
            openDataContext.postMessage({
                command: 101,
                keyList: ["score"],
                stageWidth: 100, 
                stageHeight: 100,
                gameName: "好友排行",
                score: that.score + c
            });
            
        }

        private effectTexture = ['pinkEffect_png', 'greenEffect_png', 'blueEffect_png', 'yellowEffect_png', 'redEffect_png']
        private guangboTexture = ['zibo_png', 'lvbo_png', 'lanbo_png', 'huangbo_png', 'hongbo_png']
        private starTexture = ['pinkS_png', 'greenS_png', 'blueS_png', 'yellowS_png', 'redS_png']

        private ruinItem(a, b) {
            manager.SoundManager.playSound("blockMusic_mp3")     
            
            // //文字星星特效
            let starTextMovie = manager.ResManager.getBitmap('addScoreStar_png')
            starTextMovie.anchorOffsetX = starTextMovie.width / 2
            starTextMovie.anchorOffsetY = starTextMovie.height / 2
            starTextMovie.x = b.x + b.width / 2
            starTextMovie.y = b.y + b.height / 2
            b.parent.addChild(starTextMovie)
            starTextMovie.scaleX = starTextMovie.scaleY = 0
            egret.Tween.get(starTextMovie)
                .to({scaleX: 1, scaleY: 1}, 400)
                .to({scaleX: 1, scaleY: 1}, 600)
                .to({x: 340, y: -180, alpha: 0.5}, 820)
                .call(() => {
                    starTextMovie.parent.removeChild(starTextMovie)
                }).wait(1800);

            let textScore = new egret.TextField()
            textScore.text = `${a}`
            textScore.anchorOffsetX = starTextMovie.width / 2
            textScore.anchorOffsetY = starTextMovie.height / 2
            textScore.x = b.x + b.width / 2
            textScore.y = b.y + b.height / 2
            textScore.width = starTextMovie.width
            textScore.height = starTextMovie.height
            textScore.textAlign = egret.HorizontalAlign.CENTER;
            textScore.verticalAlign = egret.VerticalAlign.MIDDLE;
            textScore.textColor = 0xff2a2a
            textScore.size = 20
            b.parent.addChild(textScore)
            textScore.scaleX = starTextMovie.scaleY = 0            
            egret.Tween.get(textScore)
                .to({scaleX: 1, scaleY: 1}, 400)
                .to({scaleX: 1, scaleY: 1}, 600)
                .to({x: 340, y: -180, alpha: 0.5}, 820)
                .call(() => {
                    textScore.parent.removeChild(textScore)
                }).wait(1800);
            
            // //旋转星星特效
            var texture = RES.getRes(this.starTexture[b.type - 1]);
            var config = RES.getRes("starEffect_json");
            var particleSys1 = new particle.GravityParticleSystem(texture,config);
            this.blockCon.addChild(particleSys1);
            particleSys1.start();
            particleSys1.emitterX = textScore.x
            particleSys1.emitterY = textScore.y
            let timer = setTimeout(() => {
                clearTimeout(timer)
                particleSys1.stop();
            },100)

            //光波特效
            let guangboMovie = manager.ResManager.getBitmap(this.guangboTexture[b.type - 1])
            guangboMovie.anchorOffsetX = guangboMovie.width / 2
            guangboMovie.anchorOffsetY = guangboMovie.height / 2
            guangboMovie.x = b.x + b.width / 2
            guangboMovie.y = b.y + b.height / 2
            b.parent.addChild(guangboMovie)
            guangboMovie.scaleX = guangboMovie.scaleY = 0
            guangboMovie.alpha = 0
            egret.Tween.get(guangboMovie)
                .to({scaleX: 0.75, scaleY: 0.75, alpha: 1}, 250)
                .to({scaleX: 1, scaleY: 1, alpha: 0}, 150)
                .call(() => {
                        guangboMovie.parent.removeChild(guangboMovie)
                    }).wait(400);

            //粒子特效
            var texture = RES.getRes(this.effectTexture[b.type - 1]);
            var config = RES.getRes("redEffect_json");
            var particleSys = new particle.GravityParticleSystem(texture,config);
            this.blockCon.addChild(particleSys);
            particleSys.start();
            particleSys.emitterX = textScore.x
            particleSys.emitterY = textScore.y
            let timer2 = setTimeout(() => {
                clearTimeout(timer2)
                particleSys.stop();
            },100)


            let timer3 = setTimeout(() => {
                clearTimeout(timer2)
                b.parent.removeChild(b)
                if(b.mark == true){
                    manager.SoundManager.playSound("boxMusic_mp3")
                    this.hasTreasureScene = true
                    this.TreasureBoxScene = new scene.TreasureBoxScene(this.level)
                    this.addChild(this.TreasureBoxScene)
                    this.TreasureBoxScene.addEventListener(events.AddTreasureBoxEvent.ADD_TREASURE, this.addTreasure, this)
                    this.TreasureBoxScene.addEventListener(events.CloseTreasureBoxPageEvent.CLOSE_TREASURE, this.closeTreasureScene, this)
                }

            }, this.animTime)
        }

        public select(a) {
            if ("play" != this.status) return !1;
            for (var b = 0; b < this.selectBlock.length; b++) this.setCheck(!1, this.selectBlock[b]);
            this.selectBlock = [];
            a = this._friends(a);
            if (!(a.length < this.minGroupSize))
                for (this.selectBlock = a, b = 0; b < this.selectBlock.length; b++) this.setCheck(!0, this.selectBlock[b])
        }
        private setCheck(a, b) {
            1 == a ? b.check = !0 : b.check = !1
        }
        private arrange() {
            for (var a, b, c = 0; c < this.data.length; c++) {
                a = [];
                for (var d = b = 0; d < this.data[c].length; d++) null == this.data[c][
                    d
                ] ? a.unshift(null) : (b++, a.push(this.data[c][d]));
                0 == b && (a.isNull = !0);
                this.data[c] = a
            }
            a = [];
            for (c = 0; c < this.data.length; c++) this.data[c].isNull || a.push(this.data[
                c]);
            this.data = a;

            for (c = 0; c < this.data.length; c++)
                for (d = 0; d < this.data[c].length; d++){
                    if(this.data[c][d]){
                        this.data[c][d].xx = c * 70 
                        this.data[c][d].yy = d * 70
                        if(this.data[c][d].xx !== this.data[c][d].x || this.data[c][d].yy !== this.data[c][d].y ){ 
                            egret.Tween.get(this.data[c][d])
                            .to({x: c * 70, y: d * 70}, 100)
                            .to({x: c * 70, y: d * 70 - 10}, 100)
                            .to({x: c * 70, y: d * 70}, 100) 
                            .to({x: c * 70, y: d * 70 - 3}, 100)
                            .to({x: c * 70, y: d * 70}, 100) 
                        }
                    }
                } 
                    
                


            this.data.forEach(item => {
                item.forEach(ele => {
                    if(ele !== null && ele.mark === true){
                        egret.Tween.get(this.goodBox).to({
                            x: ele.xx + (ele.width - this.goodBox.width) / 2,
                            y: ele.yy + (ele.height - this.goodBox.height) / 2
                        }, 100)               
                    }
                })
            })
            setTimeout(() => {
                this.touchAble = true

                console.log(this._checkEnd())

                true == this._checkEnd() && this.end(
                    "\u6728\u6709\u53ef\u4ee5\u6d88\u7ec4\u5408\u4e86\uff0c\u5c0f\u4f19\u4f34\uff01"
                )
            }, 600);
        }




        //本关游戏结束
        private end(a) {
            clearInterval(this.__timeobjArrange);
            clearInterval(this.promptTimer);
            
            this.status = "end";
            
            this.randomAdd = Math.floor(Math.random() * 3)

            this.selectBlock = []
            this.data.forEach(item => {
                item.forEach(ele => {
                    if (ele !== null){
                        ele.mark = false
                        
                        this.selectBlock.push(ele)
                    }  
                })
            })
            let d = 0
            let timer = setInterval(() => {
                if(d >= this.selectBlock.length - 1){
                    clearInterval(timer)
                }
                this.ruinItem(5, this.selectBlock[d])
                this.data[this.selectBlock[d].x / 70][this.selectBlock[d].y / 70] = null; 
                d ++                                                  
            }, 50)


            setTimeout(() => {
                this.setScore(this.score, 5 * d);

                this.onScoreProgress(this.score, this.levelScoreArr[(this.level || 1) - 1]);

                this.removeChild(this.bitmap)
                
                this.canAddSkill = true
                this.canPlaySound = true
                this.canPlaySuccessMovie = true

                if (this.score >= this.targetScore) {
                    manager.SoundManager.playSound("successMusic_mp3")                    
                    this.successScene = new scene.SuccessScene(this.score, this.level)
                    this.addChild(this.successScene)
                    this.successScene.addEventListener(events.NormalGameLevelPassedEvent.PASS_LEVEL, this.setLevel, this)

                } else {
                    wx.setStorage({
                        key: 'relive',
                        data: {
                            score: this.score,
                            level: this.level
                        }
                    })
                    this.gameOver()
                }
            }, 100 * this.selectBlock.length + 1500);

        }

        private gameOver(): void {
            console.log('gameOver')

            let endScore = this.score
            manager.GameManager.getInstance().setScore(endScore);
            this.reliveScene = new scene.ReliveScene(this.score, this.level, this.rliveNum)
            this.addChild(this.reliveScene)

            this.reliveScene.addEventListener(events.GameFinishEvent.FINISH_GAME, this.showGameOverPage, this)
            this.reliveScene.addEventListener(events.ReliveEvent.RELEVE, this.reliveDate, this)
        }

        private canPlaySuccessMovie: boolean = true;

        private onScoreProgress(current: number, total: number) {
            if(current >= total && this.canPlaySuccessMovie === true){
                this.canPlaySuccessMovie = false
                this.showSuccessMovie()
            }

            this.scorePercenage = current / total * 0.7
            if (this.scorePercenage >= 0.7 && this.canPlaySound == true) {
                this.canPlaySound = false
            }
            if (this.scorePercenage >= 1) this.scorePercenage = 1
            if (this.scorePercenage >= 1 && this.canAddSkill == true) {
                this.canAddSkill = false
                if(this.randomAdd <= 1){
                    this.addSkill1.play(0)
                    this.skillArr[0] += 1
                }else if(this.randomAdd <= 2){
                    this.addSkill2.play(0)
                    this.skillArr[1] += 1                    
                }else if(this.randomAdd <= 3){
                    this.addSkill3.play(0)
                    this.skillArr[2] += 1                    
                }
                this.updateSkillImg()
                manager.SoundManager.playSound("getSkillMusic_mp3")
            }
            let width: number = this.gameProgress1.width * this.scorePercenage;

            egret.Tween.get(this.gameProgress2)
                .to({width: width}, 1000)
        }

        private gameOverScene: scene.GameOverScene

        private successMovie: ui.MovieClip

        private showSuccessMovie() {

            console.log('showSuccessMovie')

            this.successMovie = new ui.MovieClip(manager.ResManager.getTextures("getScore_json.success_", 1, 24), 24, false);

            this.addChild(this.successMovie);
            this.successMovie.x = manager.DisplayManager.GAME_WIDTH >> 1;
            this.successMovie.y = manager.DisplayManager.GAME_HEIGHT - 200>> 1;
            this.successMovie.play(0);
            this.successMovie.addEventListener(events.MovieEvent.COMPLETE, this.onSuccessMovieComplete, this);
        }

        private onSuccessMovieComplete(){
            console.log('onSuccessMovieComplete')
            manager.DisplayManager.remove(this.successMovie);
            this.successMovie.stop();
        }

        private showGameOverPage(eve) {
            console.log('创建GameOverScene')
            if(this.hasTreasureScene == true){
                this.closeTreasureScene()
            }
            this.removeChild(this.reliveScene)
            this.gameOverScene = new scene.GameOverScene(eve.score, eve.level)
            this.addChild(this.gameOverScene)
            this.gameOverScene.addEventListener(events.GameAgainEvent.Game_AGAIN, this.gameAgain, this)
        }


        //游戏开始事件
        private beginAdd() {
            this.isBeginAdd = true
            this.BeginAddClose()
        }

        private BeginAddClose() {
            console.log('BeginAddClose')
            this.blockMovie()
            this.removeChild(this.begainAddPage)            
        }
        //钻石事件
        private showStoneScene() {
            console.log('showStoneScene')
            // manager.StatisticsManager.click(159)
            // this.stoneScene = new scene.AddStoneScene()
            // this.addChild(this.stoneScene)
            // this.stoneScene.addEventListener(events.AddStoneEvent.ADD_STONE, this.addStone, this)
            // this.stoneScene.addEventListener(events.AddStoneRejectEvent.ADD_STONE_REJECT, this.addStonePageClose, this)



            this.addStone()
        }
        private addStone() {
            manager.StatisticsManager.click(160)
            this.addStoneMovie.play(0)
            this.Stone += 10
            this.setStone(this.Stone)
            this.removeChild(this.stoneScene)            
        }
        private addStonePageClose() {
            manager.StatisticsManager.click(161)
            this.removeChild(this.stoneScene)
        }
        //宝箱事件
        private addTreasure(eve) {

            this.closeTreasureScene()

            let random = eve.random

            if(random <= 0.4){

                this.boxAddSkill2Movie.play(0)
                this.skillArr[0] += 1
            }else if(random <= 0.8){

                this.boxAddSkill1Movie.play(0)
                this.skillArr[1] += 1                
            }else{

                this.boxAddSkill3Movie.play(0)
                this.skillArr[2] += 1                
            }
            this.updateSkillImg()
            manager.SoundManager.playSound("getSkillMusic_mp3")
        }
        private closeTreasureScene() {
            this.hasTreasureScene = false
            this.removeChild(this.TreasureBoxScene)
            this.blockCon.removeChild(this.goodBox)
        }

        //复活事件
        private reliveDate() {
            if(this.rliveNum == 0){
                wx.showToast({
                title: '复活次数已用完',
                icon: 'success',
                duration: 2000
                })
                return
            }

            this.removeChild(this.reliveScene)
            this.score = wx.getStorageSync('relive').score
            this.level = wx.getStorageSync('relive').level
            this.createGameView()
            this.blockMovie()

            this.rliveNum --
        }
        //重新开始事件
        private gameAgain() {
            console.log('重新开始')
            this.removeChild(this.gameOverScene)
            this.rliveNum = 3
            this.score = 0
            this.level = 1
            this.createGameView()
            this.begainAddPage = new scene.BeginAddPage()
            this.addChild(this.begainAddPage)
            this.begainAddPage.addEventListener(events.BeginAddEvent.BEGIN_ADD, this.beginAdd, this)
            this.begainAddPage.addEventListener(events.BeginAddRejectEvent.BEGIN_ADD_REJECT, this.BeginAddClose, this)
        }

        private setStone(stone) {
            this.gameStoneText.text = `${this.Stone}`
            wx.setStorage({
                key: 'stone',
                data: {
                    stone: stone
                }
            })
        }
        private setScore(score, a) {
            let m  = score + a
            if(this.isBeginAdd == true){
                m = score + Math.floor(a * 1.2) 
            }
            this.score = m


            this.gameScore.text = `${m || 0}`


            // let c = m - score
            // let n = 0
            // let q = score
            // let timer = setInterval(() => {
            //     n ++
            //     if(n >= c){
            //         clearInterval(timer)
            //     }

            //     q += 1
            //     this.gameScore.text = `${q || 0}`
                
            // }, 1000 / c)
        }
        //更新道具显示
        private updateSkillImg(): void {
            console.log('更新道具显示' + this.skillArr)
            this.skill1Text.text = this.skillArr[0].toString()
            this.skill2Text.text = this.skillArr[1].toString()
            this.skill3Text.text = this.skillArr[2].toString()
            if(this.skillArr[0] === 0){
                this.skill1Text.text = '+'
            }if(this.skillArr[1] === 0){
                this.skill2Text.text = '+'
            }if(this.skillArr[2] === 0){
                this.skill3Text.text = '+'
            }
        }

        //c超过两秒不点击启动提示功能
        private onPrompt(): void{
            let timer = setInterval(() => {
                let randomA = Math.floor(Math.random() * this.data.length) 
                let randomB = Math.floor(Math.random() * 10)
                
                if(this.data[randomA][randomB]){
                    clearInterval(timer)
                    if(this._friends(this.data[randomA][randomB]).length >= 2){
                        this._friends(this.data[randomA][randomB]).forEach(item => {
                            egret.Tween.get(item,{ loop:true})
                                .to({alpha: 0.8}, 500)
                                .to({alpha: 1}, 500)
                        })
                        
                    }
                }
            },10)
        }


        //创建下一关
        public setLevel(eve: events.NormalGameLevelPassedEvent): void {

            console.log('创建下一关')

            this.level = eve.level;
            this.score = this.score + eve.addScore;
            this.removeChild(this.successScene);
            this.createGameView()
            this.blockMovie()
            
        }
        private update() {

        }

        private onBacked(): void {
            manager.StatisticsManager.click(150)
            console.log('onBacked')
            let event: events.SceneEvent = new events.SceneEvent(game.SceneIds.START_SCENE_ID, {});
            facade.GameFacade.getInstance().dispatchEvent(event);
        }

        private onVideoAdClose(eve: egret.Event): void {
            egret.log("视频广告播放事件:", eve.data);
            if (eve.data != null && eve.data.isEnded) {
                manager.GameManager.getInstance().adManager.removeEventListener(manager.AdManager.VIDEO_AD_CLOSE,
                    this.onVideoAdClose, this);
            }
        }



        private rankBitmapData: egret.BitmapData;
        private bitmap: egret.Bitmap;

        private recentScore(): void {

            console.log('recentScore')

            let openDataContext = wx.getOpenDataContext();
            openDataContext.postMessage({
                command: 100,
                keyList: ["score"],
                stageWidth: 100,
                stageHeight: 100,
                gameName: "好友排行",
            });
            this.rankBitmapData = new egret.BitmapData(window["sharedCanvas"]);
            this.rankBitmapData.$deleteSource = false;
            const texture = new egret.Texture();
            texture._setBitmapData(this.rankBitmapData);
            this.bitmap = new egret.Bitmap(texture);

            this.bitmap.x = 20;            
            this.bitmap.y = 150;
            
            this.addChild(this.bitmap);

            // egret.startTick((timeStarmp: number) => {
            //     egret.WebGLUtils.deleteWebGLTexture(this.rankBitmapData.webGLTexture);
            //     this.rankBitmapData.webGLTexture = null;
            //     return false;
            // }, this);
            egret.startTick(this.tickHandler, this)
        }

        public DT: number = 2000;

        private lastAt: number = 0;

        private tickHandler(dt: number): boolean {
            if (this.lastAt < 1) {
                this.lastAt = dt;
                return false;
            }
            if (dt - this.lastAt < this.DT) {
                return true;
            }
            this.lastAt = dt;
            egret.WebGLUtils.deleteWebGLTexture(this.rankBitmapData.webGLTexture);
            this.rankBitmapData.webGLTexture = null;
            return true;
        }
    }
}